<html>
<META http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<head>
<title>Section 10.1.&nbsp; Building a Form</title>
<link rel="STYLESHEET" type="text/css" href="images/style.css">
<link rel="STYLESHEET" type="text/css" href="images/docsafari.css">
</head>
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr><td><div STYLE="MARGIN-LEFT: 0.15in;">
<a href=learnphpmysql-CHP-10.html><img src="images/prev.gif" width="60" height="17" border="0" align="absmiddle" alt="Previous Page"></a>
<td align="right"><div STYLE="MARGIN-LEFT: 0.15in;">
<a href=learnphpmysql-CHP-10-SECT-2.html><img src="images/next.gif" width="60" height="17" border="0" align="absmiddle" alt="Next Page"></a>
</div></td></tr></table>
<br><table width="100%" border="0" cellspacing="0" cellpadding="0"><tr><td valign="top"><a name="learnphpmysql-CHP-10-SECT-1"></a>
<h3 id="title-IDAVPHYH" class="docSection1Title">10.1. Building a Form</h3>
<a name="IDX-CHP-10-0456"></a> 

<p class="docText">Since you'll need a place for the user to enter a search query, let's begin by building a form to handle the user's input. Every form must have these basic components:</p>
<ul><li><p class="docList">The submission type defined with the <tt>method</tt> keyword</p></li><li><p class="docList">One or more input elements defined with the <tt>input</tt> tag</p></li><li><p class="docList">The destination to go to when submitted defined with the <tt>action</tt> keyword</p></LI></ul>
<p class="docText">Let's build a simple form with a text input field called <tt>search</tt> and a <tt>submit</tt> button, as shown in <a class="docLink" href="#learnphpmysql-CHP-10-EX-1">Example 10-1</a>.</p>
<a name="learnphpmysql-CHP-10-EX-1"></a><H5 id="title-IDAGRHYH" class="docExampleTitle">Example 10-1. A simple form example</H5><p><table cellspacing="0" width="90%" border="1" cellpadding="5"><TR><td>

<pre>
 1 &lt;html&gt;
 2 &lt;head&gt;
 3  &lt;title&gt;Building a Form&lt;/title&gt;
 4 &lt;/head&gt;
 5 &lt;body&gt;
 6  &lt;form action="&lt;?php echo($_SERVER['PHP_SELF']); ?&gt;"
 7        method="get"&gt;
 8   &lt;label&gt;
 9         Search: &lt;input type="text" name="search" /&gt;
 10    &lt;/label&gt;
 11      &lt;input type="submit" value="Go!" /&gt;
 12  &lt;/form&gt;
 13 &lt;/body&gt;
 14 &lt;/html&gt;
</pre><br>

</td></TR></table></p>
<p class="docText">Place the code in <a class="docLink" href="#learnphpmysql-CHP-10-EX-1">Example 10-1</a> into a file called <span class="docEmphasis">simple.php</span> in a web-accessible directory on your web server, such as the document <tt>root</tt>. Strictly speaking, forms are defined purely by HTML, but we're using some PHP code on line 6 to reference the super global <tt>PHP_SELF</tt>. This provides a shortcut to the name of the current PHP file that handles the submission of the form data.</p>
<p class="docText">The form in <a class="docLink" href="#learnphpmysql-CHP-10-EX-1">Example 10-1</a> allows you to capture the search sting from the user for a search. Notice how we wrapped a <tt>label</tt> tag around the input where the text was; this makes the form easier to use. Since clicking on the <tt>Search:</tt> text automatically sends the cursor to the search field. On line 7, we set the form submission method to <tt>GET</tt>. This is done to insure that users can bookmark their searches and not have to come back to the page and reenter their data. Line 9 does the bulk of the work by defining the text field.</P>
<p class="docText">Accessing the <span class="docEmphasis">simple.php</span> file from your browser should generate a form similar to <a class="docLink" href="#learnphpmysql-CHP-10-FIG-1">Figure 10-1</a>. It's not terribly useful, as any value you submit just brings the same form back again, but we'll take care of that soon.</p>
<a name="learnphpmysql-CHP-10-FIG-1"></a><p><center>
<H5 class="docFigureTitle">Figure 10-1. How the sample form appears in your browser</h5>
<img border="0" alt="" id="195131084204" width="549" height="133" SRC="images/learnphpmysql_1001.jpg">
</center></p><br>
<a name="learnphpmysql-CHP-10-SECT-1.1"></a>
<h4 id="title-IDABTHYH" class="docSection2Title">10.1.1. Accessing Submitted Form Values</H4>
<a name="IDX-CHP-10-0457"></a> 
<a name="IDX-CHP-10-0458"></a> 
<a name="IDX-CHP-10-0459"></a> 

<p class="docText">Let's go ahead and modify the code in <a class="docLink" href="#learnphpmysql-CHP-10-EX-1">Example 10-1</a> to display back the search string when the form is submitted. To do this, check the value of a <tt>GET</tt> submitted field with the syntax <tt>$_GET[</tt><tt><I>field</i></tt><tt>]</tt>. Likewise, <tt>$_POST[</tt><tt><i>field</i></tt><tt>]</tt> is used to access a field when using the <tt>POST</tt> field submission.</p>
<p class="docText">Since <tt>search</tt> is the name of the field that we specified when building the form, we'll use <tt>$_GET["search"]</tt> in <a class="docLink" href="#learnphpmysql-CHP-10-EX-2">Example 10-2</a>.</P>
<a name="learnphpmysql-CHP-10-EX-2"></a><h5 id="title-IDAYUHYH" class="docExampleTitle">Example 10-2. Modifying our simple search to process the results</H5><p><table cellspacing="0" width="90%" border="1" cellpadding="5"><TR><TD>

<pre>
&lt;html&gt;
&lt;head&gt;
  &lt;title&gt;Building a Form&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;?php
$search = $_GET["search"];
$self=$_SERVER['PHP_SELF'];
if ($search != NULL )
{
('
&lt;form action="'.$_SERVER["PHP_SELF"].'" method="GET"&gt;
&lt;label&gt;Search: &lt;input type="text" name="search" /&gt;
&lt;/label&gt;
&lt;input type="submit" value="Go!" /&gt;

         &lt;/form&gt;
        ');
}
?&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre><BR>

</td></tr></table></p>
<p class="docText"><a class="docLink" href="#learnphpmysql-CHP-10-EX-2">Example 10-2</a> generates this HTML:</p>
<pre>
&lt;html&gt;
&lt;head&gt;
  &lt;title&gt;Building a Form&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;form action="/oreilly/ch10/simple.php" method="GET" /&gt;
         &lt;label&gt; Search: &lt;input type="text" name="search" id="search"&gt; &lt;/label&gt;
         &lt;input type="submit" value="Go!" /&gt;
         &lt;/form&gt;

        &lt;/body&gt;
&lt;/html&gt;
</pre><br>

<p class="docText">If you submitted a value of <tt>PHP</tt> in the search text box, you'd get output similar to <a class="docLink" href="#learnphpmysql-CHP-10-FIG-2">Figure 10-2</a>.</p>
<a name="learnphpmysql-CHP-10-FIG-2"></a><p><center>
<h5 class="docFigureTitle">Figure 10-2. The same script is now able to echo back the search string</h5>
<img border="0" alt="" id="195131084204" width="549" height="150" SRC="images/learnphpmysql_1002.jpg">
</center></p><br>
<p class="docText">When the form is submitted, the <tt>if</tt> statement notices that the <tt>$search</tt> variable has a value assigned. Instead of the script returning the HTML form, the search string is returned. So, you have the same PHP file generating the form and processing its submitted values.</p>
<p class="docText">With forms, you can specify default<a name="IDX-CHP-10-0460"></a> 
 values and use different form inputs. There are various ways you can submit the form. These will be explained in the following subsections.</p>

<a name="learnphpmysql-CHP-10-SECT-1.2"></a>
<h4 id="title-IDARWHYH" class="docSection2Title">10.1.2. Default Values</H4>
<a name="IDX-CHP-10-0461"></a> 

<p class="docText">When doing searches on a database, you might need to actually have some default values in your forms. This is useful, for example, for searching within a price range. The user doesn't always want to insert values, and it makes it that much simpler when searching. Typically, the default value for a form element is set with the <tt>value</tt> attribute; there is an exception for checkboxes that use the <tt>checked</tt> keyword. Take <a class="docLink" href="#learnphpmysql-CHP-10-EX-3">Example 10-3</a>.</p>
<a name="learnphpmysql-CHP-10-EX-3"></a><h5 id="title-IDAJXHYH" class="docExampleTitle">Example 10-3. Form default values</H5><P><table cellspacing="0" width="90%" border="1" cellpadding="5"><tr><TD>

<pre>
&lt;html&gt;
&lt;head&gt;
  &lt;title&gt;Form Default Values&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
  &lt;form action="&lt;?php echo($_SERVER['PHP_SELF']); ?&gt;" method="GET" /&gt;
    &lt;label&gt;Min Price &lt;input type="text" name="min_price" value="0" /&gt;&lt;/label&gt;&lt;br /&gt;
    &lt;label&gt;Max Price &lt;input type="text" name="max_price" value="1000" /&gt;&lt;/label&gt;
&lt;br /&gt;
    &lt;input type="submit" value="Go! /&gt;
  &lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre><br>

</td></tr></table></P>
<p class="docText">In <a class="docLink" href="#learnphpmysql-CHP-10-FIG-3">Figure 10-3</a>, the default values reflect 0 and 1000 for the minimum and maximum prices that you want to search. Depending on the area, if the user searches for an apartment to rent, this is a good starting point. We already specified a default value for the submit button as Go! in <a class="docLink" href="#learnphpmysql-CHP-10-EX-1">Example 10-1</a>.</p>
<a name="learnphpmysql-CHP-10-FIG-3"></a><p><center>
<H5 class="docFigureTitle">Figure 10-3. The default values appear in their fields</h5>
<img border="0" alt="" id="195131084204" width="485" height="140" SRC="images/learnphpmysql_1003.jpg">
</center></p><BR>

<a name="learnphpmysql-CHP-10-SECT-1.3"></a>
<h4 id="title-IDAPYHYH" class="docSection2Title">10.1.3. Types of Input</h4>
<a name="IDX-CHP-10-0462"></a> 
<a name="IDX-CHP-10-0463"></a> 
<a name="IDX-CHP-10-0464"></a> 

<p class="docText">There are many different types of input, so which one should you use? Radio buttons, checkboxes, text,<a name="IDX-CHP-10-0465"></a> 
<a name="IDX-CHP-10-0466"></a> 
 input, text areas<a name="IDX-CHP-10-0467"></a> 
<a name="IDX-CHP-10-0468"></a> 
<a name="IDX-CHP-10-0469"></a> 
 buttons . . . oh my! We'll describe each of our input options.</p>
<a name="learnphpmysql-CHP-10-SECT-1.3.1"></a>
<h5 id="title-IDAB0HYH" class="docSection3Title">10.1.3.1. Text boxes</H5>
<p class="docText">Most of the time when dealing with input from a user, you might want a string of text. A text type element is used to capture these strings from the user. The <tt>name</tt> attribute is required to process the input after a form submission as it specifies how to reference the value. When it appears in the browser, the <tt>size</tt> parameter determines the length of the text box. The <tt>maxlength</tt> parameter determines the maximum number of characters the user can place in the field. The syntax is:</P>
<pre>
&lt;input type="<tt><i>text</i></tt>" name="<tt><i>name</i></tt>" size="<tt><I>display size</i></tt>" maxlength="<tt><I>max characters allows</i></tt>" /&gt;
</pre><BR>

<p class="docText">For example, the following:</P>
<pre>
&lt;form&gt;
&lt;input type="text" name="search" size="10" maxlength="30" /&gt;
&lt;/form&gt;
</pre><BR>

<p class="docText">creates a text box like <a class="docLink" href="#learnphpmysql-CHP-10-FIG-3">Figure 10-3</a>.</p>

<a name="learnphpmysql-CHP-10-SECT-1.3.2"></a>
<h5 id="title-IDAI1HYH" class="docSection3Title">10.1.3.2. Text areas</h5>
<p class="docText">If you need a large chunk of text from a user or are going to be using a WYSIWYG editor, you need to use a text area. A text area is defined by using the <tt>textarea</tt> element. The <tt>name, cols</tt>, and <tt>rows</tt> attributes are required. The <tt>name</tt> attribute works like it did in a text box. The <tt>cols</tt> attribute specifies how many columns to create for your text area. The <tt>rows</tt> attribute specifies how many rows to create. The syntax is:</p>
<pre>
&lt;textarea name="<tt><i>name</i></tt>" cols="<tt><i># of cols</i></tt>" rows="<tt><i># of rows</i></tt>"&gt;&lt;/textarea&gt;
</pre><br>

<p class="docText">For example:</p>
<pre>
&lt;form&gt;
&lt;label&gt;Suggestion: &lt;textarea name="suggestions" cols="40" rows="5"&gt;&lt;/textarea&gt;
&lt;/label&gt;
&lt;input type="submit" value="Go! /&gt;
&lt;/form&gt;
</pre><br>

<p class="docText">might display like <a class="docLink" href="#learnphpmysql-CHP-10-FIG-4">Figure 10-4</a>.</p>
<a name="learnphpmysql-CHP-10-FIG-4"></a><P><center>
<h5 class="docFigureTitle">Figure 10-4. A simple form with a text area element</h5>
<img border="0" alt="" id="195131084204" width="542" height="183" SRC="images/learnphpmysql_1004.jpg">
</center></P><BR>

<a name="learnphpmysql-CHP-10-SECT-1.3.3"></a>
<h5 id="title-IDA52HYH" class="docSection3Title">10.1.3.3. Checkboxes</H5>
<p class="docText">A checkbox is useful when you want to give users several different options, especially when they're allowed to select each choice individually. Use checkboxes<a name="IDX-CHP-10-0470"></a> 
<a name="IDX-CHP-10-0471"></a> 
<a name="IDX-CHP-10-0472"></a> 
 only when you have a few options to give to a user; otherwise, there is a different type of input that you would want to use. This is called a <span class="docEmphasis">select</span>, which we'll talk about in a bit. For a checkbox, set the input type to <tt>checkbox</tt>. The name and value attributes are also required. If the value is set to <tt>checked</tt>, the checkbox is checked by default.</p>
<p class="docText">The syntax is:</p>
<pre>
&lt;input type="checkbox" name="<tt><i>name</I></tt>" value="<tt><i>checkbox value</i></tt>" /&gt;
</pre><BR>

<p class="docText">For example:</p>
<pre>
&lt;form&gt;
&lt;fieldset&gt;
&lt;label&gt;Italian &lt;input type="checkbox" name="food[]" value="Italian" /&gt;&lt;/label&gt;
&lt;label&gt;Mexican &lt;input type="checkbox" name="food[]" value="Mexican" /&gt;&lt;/label&gt;
&lt;label&gt;Chinese &lt;input type="checkbox" name="food[]" value="Chinese"
checked="checked" /&gt;&lt;/label&gt;
&lt;/fieldset&gt;
&lt;input type="submit" value="Go! /&gt;
&lt;/form&gt;
</pre><br>

<p class="docText">This displays the box shown in <a class="docLink" href="#learnphpmysql-CHP-10-FIG-5">Figure 10-5</a>.</P>
<a name="learnphpmysql-CHP-10-FIG-5"></a><p><center>
<h5 class="docFigureTitle">Figure 10-5. A sample form with checkboxes</h5>
<img border="0" alt="" id="195131084204" width="499" height="154" SRC="images/learnphpmysql_1005.jpg">
</center></p><BR>

<a name="learnphpmysql-CHP-10-SECT-1.3.4"></a>
<H5 id="title-IDA54HYH" class="docSection3Title">10.1.3.4. Radio buttons</h5>
<p class="docText">Radio buttons behave just like the presets on a radio. They are like checkboxes, except you can only select one radio button at a time. To create a radio button, set the type to <tt>radio</tt>. The name and value attributes are required. All of the radio buttons<a name="IDX-CHP-10-0473"></a> 
<a name="IDX-CHP-10-0474"></a> 
<a name="IDX-CHP-10-0475"></a> 
 in a group must use the same name to allow for only one value. The syntax is:</p>
<pre>
&lt;input type="radio" name="<tt><i>name</i></tt>" value="<tt><I>radio button value</i></tt>" /&gt;
</pre><BR>

<p class="docText">For example:</p>
<pre>
&lt;form&gt;
&lt;fieldset&gt;
&lt;label&gt;Italian &lt;input type="radio" name="food" value="Italian" /&gt;&lt;/label&gt;
&lt;label&gt;Mexican &lt;input type="radio" name="food" value="Mexican" /&gt;&lt;/label&gt;
&lt;label&gt;Chinese &lt;input type="radio" name="food" value="Chinese"
checked="checked"  /&gt;&lt;/label&gt;
&lt;/fieldset&gt;
&lt;input type="submit" value="Go! /&gt;
&lt;/form&gt;
</pre><BR>

<p class="docText">This looks like <a class="docLink" href="#learnphpmysql-CHP-10-FIG-6">Figure 10-6</a>.</P>
<a name="learnphpmysql-CHP-10-FIG-6"></a><P><center>
<h5 class="docFigureTitle">Figure 10-6. The same choices are available as before, but the radio buttons are round</h5>
<img border="0" alt="" id="195131084204" width="497" height="147" SRC="images/learnphpmysql_1006.jpg">
</center></p><br>
<p class="docText"><a class="docLink" href="#learnphpmysql-CHP-10-FIG-6">Figure 10-6</a> allows only one type of food to be selected.</p>

<a name="learnphpmysql-CHP-10-SECT-1.3.5"></a>
<h5 id="title-IDADBIYH" class="docSection3Title">10.1.3.5. Hidden</h5>
<a name="IDX-CHP-10-0476"></a> 
<a name="IDX-CHP-10-0477"></a> 
<a name="IDX-CHP-10-0478"></a> 

<p class="docText">Hidden form elements allow you to send information from the form to the script that processes the data without that information being visible to the user. This may be information such as whether the forms' submit button was pressed, or perhaps a username. The syntax is:</p>
<pre>
&lt;input type="hidden" name="<tt><i>name</i></tt>" value="<tt><i>hidden value</i></tt>" /&gt;
</pre><br>

<p class="docText">For example:</p>
<pre>
&lt;form&gt;
&lt;input type="hidden" name="submitted" value="true" /&gt;
&lt;/form&gt;
</pre><BR>

<p class="docText"><tt>HIDDEN</tt> is a <tt>TYPE</tt> attribute value to the <tt>INPUT</tt> element for forms. It indicates a form field that does not appear visibly in the document and that the user does not interact with. It can be used to transmit stale information about the client or server. Hidden fields can be viewed via the Page Source. Therefore, it's unadvisable to put passwords in a hidden field.</p>

<a name="learnphpmysql-CHP-10-SECT-1.3.6"></a>
<h5 id="title-IDAOCIYH" class="docSection3Title">10.1.3.6. Selects</H5>
<a name="IDX-CHP-10-0479"></a> 
<a name="IDX-CHP-10-0480"></a> 

<p class="docText">Selects present a list of options to the user. You can specify whether a user can select only one or many items from the list. The <tt>&lt;select&gt;</tt> element defines a select list. Each item on the list is specified with the <tt>option</tt> element. The syntax is:</P>
<pre>
&lt;select name="<tt><i>name</I></tt>"&gt; &lt;option&gt;<tt><i>Label of Option</i></tt>&lt;/option&gt; &lt;/select&gt;
</pre><br>

<p class="docText">Additionally, there are several attributes that can be set within <tt>&lt;select&gt;</tt>:</P>
<ul><li><p class="docList">The <tt>name</tt> attribute is required and specifies how to access the data after form submission.</P></li><li><p class="docList">The <tt>size</tt> attribute specifies how many lines of the list appear in the browser window. The default is a drop-down list.</P></li><li><p class="docList">The <tt>multiple</tt> attributes allow the user to select more than one item from the list.</p></li></UL>
<p class="docText">There are two commonly used attributes for <tt>&lt;option&gt;</tt>:</P>
<ul><li><p class="docList">The <tt>selected</tt> attribute specifies a default selection.</p></li><LI><p class="docList">The <tt>value</tt> attribute specifies a value that is different from the label of the option. If no <tt>value</tt> is specified, the label of the option is used as the value.</p></LI></ul>
<P><table border="0" bgcolor="black" cellspacing="0" cellpadding="1" width="90%" align="center"><TR><TD><table bgcolor="white" width="100%" border="0" cellspacing="0" cellpadding="6"><tr><td width="60" valign="top"><img src="images/tip_yellow.jpg" width="50" height="54" alt=""></td><td valign="top">
<p class="docText">A selection list that doesn't have multiple attributes can have only one option selected by default.</p>
</td></tr></table></td></tr></table></p><br>
<p class="docText">A common use for a select list is providing options from which a user may choose, such as that created in <a class="docLink" href="#learnphpmysql-CHP-10-EX-4">Example 10-4</a>.</p>
<a name="learnphpmysql-CHP-10-EX-4"></a><h5 id="title-IDAOFIYH" class="docExampleTitle">Example 10-4. Multiple book types</h5><P><table cellspacing="0" width="90%" border="1" cellpadding="5"><tr><td>

<pre>
&lt;form&gt;
&lt;select name="media" multiple="multiple"&gt;
  &lt;option&gt;&lt;/option&gt;
  &lt;option&gt;Hard Cover&lt;/option&gt;
  &lt;option&gt;Soft Cover&lt;/option&gt;
  &lt;option&gt;Reference&lt;/option&gt;
  &lt;option&gt;Audio Books&lt;/option&gt;
&lt;/select&gt;
&lt;/form&gt;
</pre><BR>

</TD></tr></table></P>
<p class="docText"><a class="docLink" href="#learnphpmysql-CHP-10-FIG-7">Figure 10-7</a> shows the list built from the code in <a class="docLink" href="#learnphpmysql-CHP-10-EX-4">Example 10-4</a>.</p>
<a name="learnphpmysql-CHP-10-FIG-7"></a><p><center>
<h5 class="docFigureTitle">Figure 10-7. Multiple items selected from the list</H5>
<img border="0" alt="" id="195131084204" width="530" height="176" SRC="images/learnphpmysql_1007.jpg">
</center></p><br>
<p class="docText">The first option in the list is actually a blank entry. This is useful for detecting if a user hasn't made any changes to a list.</P>


<a name="learnphpmysql-CHP-10-SECT-1.4"></a>
<h4 id="title-IDATGIYH" class="docSection2Title">10.1.4. Working with Multiple Values</h4>
<a name="IDX-CHP-10-0481"></a> 

<p class="docText">Having checkboxes and radio buttons creates a new problem. You can't use a single value when processing the results of a group of checkboxes with the same name or elements from a select list. <a class="docLink" href="#learnphpmysql-CHP-10-EX-5">Example 10-5</a> shows an example.</P>
<a name="learnphpmysql-CHP-10-EX-5"></a><h5 id="title-IDAHHIYH" class="docExampleTitle">Example 10-5. A form with checkboxes using the same name to store multiple values</h5><p><table cellspacing="0" width="90%" border="1" cellpadding="5"><tr><TD>

<a name="IDX-CHP-10-0482"></a> 

<pre>
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Using Default Checkbox Values&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;?php
$food = $_GET["food"];
if (!empty($food)){
echo "The foods selected are: &lt;strong&gt;";
foreach($food as $foodstuff){
echo '&lt;br /&gt;'.$foodstuff;
}
echo "&lt;/strong&gt;.";
}
else {
echo ('
&lt;form action="'.$_SERVER["PHP_SELF"].'" method="GET"&gt;
&lt;fieldset&gt;
&lt;label&gt;
Italian
&lt;input type="checkbox" name="food[]" value="Italian" /&gt;
&lt;/label&gt;
&lt;label&gt;
Mexican
&lt;input type="checkbox" name="food[]" value="Mexican" /&gt;
&lt;/label&gt;
&lt;label&gt;
Chinese
&lt;input type="checkbox" name="food[]" value="Chinese" checked="checked" /&gt;
&lt;/label&gt;
&lt;/fieldset&gt;
&lt;input type="submit" value="Go!" /&gt;');
}
?&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre><BR>

</td></tr></table></p>
<p class="docText"><a class="docLink" href="#learnphpmysql-CHP-10-EX-5">Example 10-5</a> produces something like <a class="docLink" href="#learnphpmysql-CHP-10-FIG-8">Figure 10-8</a>.</p>
<a name="learnphpmysql-CHP-10-FIG-8"></a><P><center>
<h5 class="docFigureTitle">Figure 10-8. The Chinese checkbox is checked by default</H5>
<img border="0" alt="" id="195131084204" width="499" height="154" SRC="images/learnphpmysql_1008.jpg">
</center></p><BR>
<p class="docText">You gave the user the choice of three different ethnic foods: Italian, Mexican, and Chinese. In this example, the user can check multiple checkboxes. Therefore, you need to access more than a single value from the name of the checkbox when you process the form submission in PHP. We'll place a pair of brackets (<tt>[]</tt>) after the field's <tt>name</tt> attribute to send the results in an array.</P>
<p class="docText">In the following code, the <tt>name</tt> attribute is set to <tt>food[]</tt> instead of <tt>food</tt>. Without the array, if a user checks multiple foods, his selections would be overwritten by the last food checked in the list. Placing closed brackets after the input name signifies an array. Since you want to have one choice checked already, give it an attribute of <tt>checked</tt>, and then set it to <tt>checked</tt>. This sets the checkbox to be set by default in a user's browser.</P>
<pre>
&lt;html&gt;
&lt;head&gt;
  &lt;title&gt;Using Default Checkbox Values&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;?php
$food=$_GET[food];
$self=$_SERVER['PHP_SELF'];
if (!empty($food))
{
  echo "The foods selected are:&lt;br /&gt;";
  foreach($_GET[food] as $foodstuf)
  {
   echo "&lt;strong&gt;$foodstuf&lt;/strong&gt;&lt;br /&gt;";
  }
}
else
{
  echo ("&lt;form action=\"$self\" ");
  echo ('method="get"&gt;
   &lt;fieldset&gt;
    &lt;label&gt;Italian &lt;input type="checkbox" name="food[]" value="Italian" /&gt;&lt;/label&gt;
    &lt;label&gt;Mexican &lt;input type="checkbox" name="food[]" value="Mexican" /&gt;&lt;/label&gt;
    &lt;label&gt;Chinese &lt;input type="checkbox" name="food[]" value="Chinese"
checked="checked" /&gt;&lt;/label&gt;
   &lt;/fieldset&gt;
    &lt;input type="submit" value="Go!" &gt;
        ');
}
?&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre><br>

<p class="docText">If you select two checkboxes, you'll see the screen in <a class="docLink" href="#learnphpmysql-CHP-10-FIG-9">Figure 10-9</a>.</p>
<a name="learnphpmysql-CHP-10-FIG-9"></a><p><center>
<h5 class="docFigureTitle">Figure 10-9. Selecting Italian and Chinese</h5>
<img border="0" alt="" id="195131084204" width="452" height="142" SRC="images/learnphpmysql_1009.jpg">
</center></p><br>
<p class="docText">The screen in <a class="docLink" href="#learnphpmysql-CHP-10-FIG-9">Figure 10-9</a> produces the screen in <a class="docLink" href="#learnphpmysql-CHP-10-FIG-10">Figure 10-10</a>, when submitted.</p>
<a name="learnphpmysql-CHP-10-FIG-10"></a><p><center>
<h5 class="docFigureTitle">Figure 10-10. Each check field is displayed</h5>
<img border="0" alt="" id="195131084204" width="452" height="142" SRC="images/learnphpmysql_1010.jpg">
</center></p><br>
<p class="docText">You can set up radio buttons in the same way, but <tt>name</tt> should be set to <tt>food</tt> instead of <tt>food[]</tt>, since radio buttons tell users they have only one choice.</p>
<p class="docText">Lastly, notice in the preceding code that the checkboxes are wrapped around a <tt>fieldset</tt> tag. This is used to logically define a set of data.</P>

<a name="learnphpmysql-CHP-10-SECT-1.5"></a>
<h4 id="title-IDADLIYH" class="docSection2Title">10.1.5. Validating Data</h4>
<a name="IDX-CHP-10-0483"></a> 
<a name="IDX-CHP-10-0484"></a> 
<a name="IDX-CHP-10-0485"></a> 
<a name="IDX-CHP-10-0486"></a> 

<p class="docText">Whenever you are taking data from a user, you should always validate it. If you do not validate the user's input, it can cause many problemsmost importantly, substantial security risks.</P>
<p class="docText">Validating input is not complicated. We'll go over the most common PHP functions that are used to sanitize data from users.</P>
<a name="learnphpmysql-CHP-10-SECT-1.5.1"></a>
<h5 id="title-IDAAMIYH" class="docSection3Title">10.1.5.1. Validating checkboxes, radio buttons, and selects</H5>
<p class="docText">Validating data that comes from checkboxes, radio buttons, or selects is easier than validating free format fields such as text boxes, because the value should only be one of the predefined values. To ensure this, store all of the options in an array and make sure the user input is part of the array when you process the data. We'll look at the code for checking input from a single selection (in other words, only one checkbox, radio button, or other selection), as shown in <a class="docLink" href="#learnphpmysql-CHP-10-EX-6">Example 10-6</a>.</p>
<a name="learnphpmysql-CHP-10-EX-6"></a><h5 id="title-IDAOMIYH" class="docExampleTitle">Example 10-6. Checking input from a radio button or a single select</h5><P><table cellspacing="0" width="90%" border="1" cellpadding="5"><tr><td>

<pre>
&lt;?php
$options = array('option 1', 'option 2', 'option 3');
// Coming from a checkbox or a multiple select statement
$valid = true;
if (is_array($_GET['input'])) {
$valid = true;
foreach($_GET['input'] as $input) {
if (!in_array($input, $options)) {
$valid = false;
}
}
if ($valid) {
// process input
}
}
?&gt;
</pre><BR>

</td></tr></table></P>

<a name="learnphpmysql-CHP-10-SECT-1.5.2"></a>
<h5 id="title-IDAYMIYH" class="docSection3Title">10.1.5.2. Validating text boxes and text areas</h5>
<a name="IDX-CHP-10-0487"></a> 
<a name="IDX-CHP-10-0488"></a> 

<p class="docText">To validate text boxes and text areas, you first need to gather what information is valid and what isn't. Also, you don't want to allow the user to enter nothing. You can spend as little time as checking to see whether a string is empty, or you can build more complex expressions to check for the presence of certain characters, such as the <tt>@</tt> in an email address. You can use the code in <a class="docLink" href="#learnphpmysql-CHP-10-EX-7">Example 10-7</a> to make sure the input is acceptable.</p>
<a name="learnphpmysql-CHP-10-EX-7"></a><h5 id="title-IDARNIYH" class="docExampleTitle">Example 10-7. Checking input from a checkbox or a multiple select</H5><P><table cellspacing="0" width="90%" border="1" cellpadding="5"><tr><td>

<pre>
&lt;?php
    $options = array('option 1', 'option 2', 'option 3');

    //coming from a checkbox or a multiple select statement
    $valid = true;
    if (is_array($_GET['input'])) {
      $valid = true;
      foreach($_GET['input'] as $input) {
        if (!in_array($input, $options)) {
          $valid = false;
        }
      }
      if ($valid) {
        //process input
      }
    }
?&gt;
</pre><br>

</td></TR></table></p>
<p class="docText">Since we haven't given you much tangible, sink-your-teeth-into-it PHP code, we're going to give you a great example of how PHP can easily create a conversion tool. Using conversion tools, you could convert from Fahrenheit to Celsius, or U.S. Units of Measurement to Metric. Pretty cool, huh?</P>


<a name="learnphpmysql-CHP-10-SECT-1.6"></a>
<h4 id="title-IDA4NIYH" class="docSection2Title">10.1.6. Building a Feet-to-Meters Converter in PHP</H4>
<p class="docText">We're going to show you the power of PHP by creating a feet-to-meters converter<a name="IDX-CHP-10-0489"></a> 
 application, shown in <a class="docLink" href="#learnphpmysql-CHP-10-EX-8">Example 10-8</a>, which would be handy if your web site is used internationally.</P>
<a name="learnphpmysql-CHP-10-EX-8"></a><H5 id="title-IDASOIYH" class="docExampleTitle">Example 10-8. PHP feet-to-meters converter</h5><p><table cellspacing="0" width="90%" border="1" cellpadding="5"><tr><td>

<pre>
&lt;head&gt;
&lt;title&gt;Feet to meters conversion&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;?php
// Check to see if the form has been submitted
$feet = $_GET["feet"];
if ($_GET[feet] != NULL){
echo "&lt;strong&gt;$feet&lt;/strong&gt; feet converts to &lt;strong&gt;";
echo $feet * 0.3048;
echo "&lt;/strong&gt; meters.&lt;br /&gt;";
}
?&gt;
&lt;form action="&lt;?php echo($_SERVER['PHP_SELF']); ?&gt;" method="GET"&gt;
&lt;label&gt;Feet:
&lt;input type="text" name="feet" value="&lt;?php echo $feet; ?&gt;" /&gt;
&lt;/label&gt;
&lt;input type="submit" value="Convert!" /&gt;
&lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre><br>

</td></tr></table></p>
<p class="docText">This self-processing form collects a measurement in feet, multiplies that measurement by a standard conversion factor, and then prints out the results. Since you still have the original value for feet in the <tt>$feet</tt> variable from the form submission, you use it as an initial value when displaying the Feet user input field in the form. <a class="docLink" href="#learnphpmysql-CHP-10-FIG-11">Figure 10-11</a> shows the results of entering <tt>12</tt> and clicking Convert.</p>
<a name="learnphpmysql-CHP-10-FIG-11"></a><p><center>
<h5 class="docFigureTitle">Figure 10-11. Simply convert feet to meters using a mathematical formula</h5>
<img border="0" alt="" id="195131084204" width="549" height="233" SRC="images/learnphpmysql_1011.jpg">
</center></p><br>

<a name="learnphpmysql-CHP-10-SECT-1.7"></a>
<H4 id="title-IDAUPIYH" class="docSection2Title">10.1.7. Building a Time Zone Conversion Utility in PHP</h4>
<a name="IDX-CHP-10-0490"></a> 
<a name="IDX-CHP-10-0491"></a> 

<p class="docText">Now that you've learned how to do a variety of tasks, let's put it all together to get an idea of what can be done in PHP. <a class="docLink" href="#learnphpmysql-CHP-10-EX-9">Example 10-9</a> uses forms, arrays, conditionals, looping, and date strings. These all work together to bring you a handy tool for converting between some common time zones.</p>
<a name="learnphpmysql-CHP-10-EX-9"></a><H5 id="title-IDAQQIYH" class="docExampleTitle">Example 10-9. Converting between time zones based on user input</H5><p><table cellspacing="0" width="90%" border="1" cellpadding="5"><TR><td>

<pre>
 1 &lt;html&gt;
 2 &lt;head&gt;
 3 &lt;title&gt;Time Zone Converter&lt;/title&gt;
 4 &lt;/head&gt;
 5 &lt;body&gt;
 6 &lt;?php
 7 // An array holds the standard time zone strings
 8 $time_zones = array("Asia/Hong_Kong",
 9 "Africa/Cairo",
 10 "Europe/Paris",
 11 "Europe/Madrid",
 12 "Europe/London",
 13 "Asia/Tokyo",
 14 "America/New_York",
 15 "America/Los_Angeles",
 16 "America/Chicago");
 17 // Check to see if the form has been submitted
 18 if ($_GET["start_time"] != NULL){
 19 $start_time_input = $_GET["start_time"];
 20 $start_tz = $_GET["start_tz"];
 21 $end_tz = $_GET["end_tz"];
 22 putenv("TZ=$start_tz");
 23 $start_time = strtotime($start_time_input);
 24 echo "&lt;p&gt;&lt;strong&gt;";
 25 echo date("h:i:sA",$start_time)."\n";
 26 echo "&lt;/strong&gt;";
 27 putenv("TZ=$end_tz");
 28
 29 echo "in $start_tz becomes ";
 30 echo "&lt;strong&gt; ";
 31 echo date("h:i:sA",$start_time)."\n";
 32 echo "&lt;/strong&gt;";
 33 echo " in $end_tz.&lt;/p&gt;&lt;hr /&gt;";
 34 }
 35 ?&gt;
 36 &lt;form action="&lt;?php echo($_SERVER['PHP_SELF']); ?&gt;" method="GET"&gt;
 37 &lt;label&gt;
 38 Your Time:
 39 &lt;input type="text" name="start_time" value="&lt;?php echo $start_time_input; ?&gt;" /&gt;
 40 &lt;/label&gt; in
 41 &lt;select name="start_tz"&gt;
 42 &lt;?php
 43 foreach ($time_zones as $tz) {
 44 echo '&lt;option';
 45 if (strcmp($tz, $start_tz) == 0){
 46 echo ' selected="selected"';
 47 }
 48 echo "&gt;$tz&lt;/option&gt;";
 49 }
 50 ?&gt;
 51 &lt;/select&gt;
 52 &lt;p&gt;Convert to:
 53 &lt;select name="end_tz"&gt;
 54 &lt;?php
 55 foreach ($time_zones as $tz) {
 56 echo '&lt;option';
 57 if (strcmp($tz, $end_tz) == 0){
 58 echo ' selected="selected"';
 59 }
 60 echo "&gt;$tz&lt;/option&gt;";
 61 }
 62
 63 ?&gt;
 64 &lt;/select&gt;
 65 &lt;input type="submit" value="Convert!"&gt;
 66 &lt;/form&gt;
 67 &lt;/body&gt;
 68
 69 &lt;/html&gt;
</pre><br>

</td></TR></table></p>
<p class="docText">Here's what happened in <a class="docLink" href="#learnphpmysql-CHP-10-EX-9">Example 10-9</a> on a line-by-line basis:</p>
<UL><li><p class="docList">Lines 9 through 17 populate an array with a handful of time zones from around the world.</p></LI><li><p class="docList">Line 20 checks to see whether there is a value for the <tt>$start_time</tt>. It's assumed that if there's a value, then the code has been launched in response to the user submitting the form.</p></li><li><p class="docList">Line 25 sets the environmental variable that defines the current time zone. PHP uses this for both the <tt>strtotime</tt> and <tt>date</tt> functions.</P></LI><li><p class="docList">Line 42 begins building the user input form. We'll give the user the chance to make another time comparison.</p></li><li><p class="docList">Lines 43 through 49 and 55 through 61 loop through the time zones in the array. They also check whether the passed-in value from the form submission matches a time zone value. If it does, insert the <tt>selected</tt> attribute so that the time zone settings are remembered from the last form submission.</P></li></UL>
<p class="docText"><a class="docLink" href="#learnphpmysql-CHP-10-FIG-12">Figure 10-12</a> show an example of converting the time from Chicago to Paris.</p>
<a name="learnphpmysql-CHP-10-FIG-12"></a><P><center>
<H5 class="docFigureTitle">Figure 10-12. Converting Chicago time to Paris time</H5>
<img border="0" alt="" id="195131084204" width="549" height="208" SRC="images/learnphpmysql_1012.jpg">
</center></p><br>

<a name="learnphpmysql-CHP-10-SECT-1.8"></a>
<h4 id="title-IDATSIYH" class="docSection2Title">10.1.8. Querying the Database with Form Data</h4>
<a name="IDX-CHP-10-0492"></a> 
<a name="IDX-CHP-10-0493"></a> 
<a name="IDX-CHP-10-0494"></a> 

<p class="docText">Once you've validated your data, you're ready to start using information from the forms in your database queries. <a class="docLink" href="#learnphpmysql-CHP-10-EX-10">Example 10-10</a> creates a function called <tt>query_db</tt> from the code in <a class="docLink" href="learnphpmysql-CHP-7.html#learnphpmysql-CHP-7">Chapter 7</a> for displaying authors with a change to line 11 that allows matching the title with a <tt>LIKE</tt> search clause. <tt>LIKE</tt> and <tt>NOT LIKE</tt> are usually used with strings and possibly with wildcards, such as the underscore (<tt>_</tt>) and the percentage sign (<tt>%</tt>).</p>
<ul><li><p class="docList">The underscore (<tt>_</tt>) matches a single character.</p></li><li><p class="docList">The percent sign (<tt>%</tt>) matches zero or more characters.</p></li></ul>
<p class="docText">In <a class="docLink" href="#learnphpmysql-CHP-10-EX-10">Example 10-10</a>, the function takes a single parameter and searches for the specific book title you're looking to find.</p>
<a name="learnphpmysql-CHP-10-EX-10"></a><H5 id="title-IDA1UIYH" class="docExampleTitle">Example 10-10. Combining form processing and database querying</h5><p><table cellspacing="0" width="90%" border="1" cellpadding="5"><TR><TD>

<pre>
 1 ?php
 2 function query_db($qstring) {
 3 include('db_login.php');
 4 require_once('DB.php');
 5 $connection = DB::connect("mysql://$db_username:$db_password@$db_host/$db_database");
 6
 7 if (DB::isError($connection)){
 8 die ("Could not connect to the database: &lt;br /&gt;". DB::errorMessage($connection));
 9 }
 10 $query = "SELECT * FROM `books` NATURAL JOIN `authors`
 11 WHERE `books`.`title` like '%$qstring%'";
 12 $result = $connection-&gt;query($query);
 13 if (DB::isError($result)){
 14 die("Could not query the database:&lt;br /&gt;".
 15 $query." ".DB::errorMessage($result));
 16 }
 17 echo ('&lt;table border="1"&gt;');
 18 echo "&lt;tr&gt;&lt;th&gt;Title&lt;/th&gt;&lt;th&gt;Author&lt;/th&gt;&lt;th&gt;Pages&lt;/th&gt;&lt;/tr&gt;";
 19 while ($result_row = $result-&gt;fetchRow()) {
 20 echo "&lt;tr&gt;&lt;td&gt;";
 21 echo $result_row[1] . '&lt;/td&gt;&lt;td&gt;';
 22 echo $result_row[4] . '&lt;/td&gt;&lt;td&gt;';
 23 echo $result_row[2] . '&lt;/td&gt;&lt;/tr&gt;';
 24 }
 25 echo ("&lt;/table&gt;");
 26 $connection-&gt;disconnect();
 27 }
 28 ?&gt;
 29 &lt;html&gt;
 30 &lt;head&gt;
 31 &lt;title&gt;Building a Form&lt;/title&gt;
 32 &lt;/head&gt;
 33 &lt;body&gt;
 34 &lt;?php
 35 $search = $_GET["search"];
 36 $self = $_SERVER['PHP_SELF'];
 37 if ($search != NULL){
 38 echo "The search string is: &lt;strong&gt;$search&lt;/strong&gt;.";
 39 query_db($search);
 40 }
 41 else {
 42 echo ('
 43 &lt;form action="'.$self.'" method="get"&gt;
 44 &lt;label&gt;Search:
 45 &lt;input type="text" name="search" id="search" /&gt;
 46 &lt;/label&gt;
 47 &lt;input type="submit" value="Go!" /&gt;
 48 &lt;/form&gt;
 49 ');
 50 }
 51
 52 ?&gt;
 53 &lt;/body&gt;
 54 &lt;/html&gt;
</pre><br>

</TD></tr></table></p>
<p class="docText">Line 50 completes the processing of the form data. The search string is sent to the <tt>query_db</tt> function. This example shows a fairly simple search done by searching a words table, and then outputting the results on the pages that are being used, as shown in <a class="docLink" href="#learnphpmysql-CHP-10-FIG-13">Figure 10-13</a>.</p>
<a name="learnphpmysql-CHP-10-FIG-13"></a><P><center>
<h5 class="docFigureTitle">Figure 10-13. We see our familiar text box for searching</h5>
<img border="0" alt="" id="195131084204" width="549" height="198" SRC="images/learnphpmysql_1013.jpg">
</center></P><br>
<p class="docText">Searching for "ing" matches one title, shown in <a class="docLink" href="#learnphpmysql-CHP-10-FIG-14">Figure 10-14</a>.</p>
<a name="learnphpmysql-CHP-10-FIG-14"></a><P><center>
<h5 class="docFigureTitle">Figure 10-14. The book titles that contain "ing" are displayed</h5>
<img border="0" alt="" id="195131084204" width="549" height="147" SRC="images/learnphpmysql_1014.jpg">
</center></p><br>
<p class="docText">Shortening up the search string to <tt>in</tt> outputs an additional title, as shown in <a class="docLink" href="#learnphpmysql-CHP-10-FIG-15">Figure 10-15</a>.</P>
<a name="learnphpmysql-CHP-10-FIG-15"></a><P><center>
<h5 class="docFigureTitle">Figure 10-15. Shortening the search string gives more results</h5>
<img border="0" alt="" id="195131084204" width="549" height="191" SRC="images/learnphpmysql_1015.jpg">
</center></p><br>
<p class="docText">While this code works pretty well, it's starting to get more complicated and intricate than some people are comfortable with. The solution is to break out the HTML from the PHP.</P>


</TD></TR></table>
<br>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr><td><div STYLE="MARGIN-LEFT: 0.15in;">
<a href=learnphpmysql-CHP-10.html><img src="images/prev.gif" width="60" height="17" border="0" align="absmiddle" alt="Previous Page"></a>
<td align="right"><div STYLE="MARGIN-LEFT: 0.15in;">
<a href=learnphpmysql-CHP-10-SECT-2.html><img src="images/next.gif" width="60" height="17" border="0" align="absmiddle" alt="Next Page"></a>
</div></td></tr></table>
<script type="text/javascript"><!--
google_ad_client = "pub-0203281046321155";
google_alternate_ad_url = "http://www.bookhtml.com/adbrite.htm";
google_ad_width = 728;
google_ad_height = 90;
google_ad_format = "728x90_as";
google_ad_type = "text_image";
google_ad_channel ="4867465545";
google_color_border = "FFFFFF";
google_color_link = "0000FF";
google_color_bg = "FFFFFF";
google_color_text = "000000";
google_color_url = "0000FF";
//--></script>
<script type="text/javascript"
  src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</html>
